package response

import (
	"gin-vue-admin/global"
	"net/http"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type Response struct {
	Code int         `json:"code"` // 状态码
	Data interface{} `json:"data"`
	Msg  string      `json:"msg"` // 响应信息
}

type Pagination struct {
	PageNum  int
	PageSize int
	Total    int64
}

const (
	ERROR   = http.StatusInternalServerError
	SUCCESS = http.StatusOK
)

func Result(code int, data interface{}, msg string, c *gin.Context) {
	// 开始时间
	c.JSON(http.StatusOK, Response{
		code,
		data,
		msg,
	})
}

func Ok(c *gin.Context) {
	Result(SUCCESS, map[string]interface{}{}, "操作成功", c)
}

func OkWithMessage(message string, c *gin.Context) {
	Result(SUCCESS, map[string]interface{}{}, message, c)
}

func OkWithData(data interface{}, c *gin.Context) {
	Result(SUCCESS, data, "操作成功", c)
}

func OkWithDetailed(data interface{}, message string, c *gin.Context) {
	Result(SUCCESS, data, message, c)
}

func Fail(c *gin.Context) {
	Result(ERROR, map[string]interface{}{}, "操作失败", c)
}

func FailWithMessage(message string, c *gin.Context) {
	Result(ERROR, map[string]interface{}{}, message, c)
}

func FailWithDetailed(data interface{}, message string, c *gin.Context) {
	Result(ERROR, data, message, c)
}

func RespondOperate(err error, c *gin.Context) {
	if err != nil {
		global.GVA_LOG.Error(err.Error(), zap.Any("err", err))
		FailWithMessage(err.Error(), c)
	} else {
		Ok(c)
	}
}

func RespondData(data interface{}, err error, c *gin.Context) {
	if err != nil {
		global.GVA_LOG.Error("获取失败", zap.Any("err", err))
		FailWithMessage("获取失败", c)
	} else {
		OkWithData(data, c)
	}
}

func RespondList(rows interface{}, pagination Pagination, err error, c *gin.Context) {
	if err != nil {
		global.GVA_LOG.Error("获取失败", zap.Any("err", err))
		FailWithMessage("获取失败", c)
	} else {
		OkWithDetailed(PageResult{
			Rows:     rows,
			Total:    pagination.Total,
			PageNum:  pagination.PageNum,
			PageSize: pagination.PageSize,
		}, "获取成功", c)
	}
}
